﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;

namespace BlogTruyen.UserControls
{
    public partial class Home : UserControl
    {
        private ViewModels.Home Data;

        public event EventHandler StoryTap;
        public Home()
        {
            InitializeComponent();
            Data = new ViewModels.Home();
            DataContext = Data;
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            if (!Data.isLoaded)
            {
                var webClient = API.GetWebClient();
                webClient.DownloadStringCompleted += webClient_DownloadStringCompleted;
                webClient.DownloadStringAsync(new Uri("http://blogtruyen.com/trangchu", UriKind.Absolute));
                busyIndicator.IsRunning = true;
            }
        }

        void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (API.CheckWebClient(e))
            {
                Data.LoadHtml(e.Result);
            }
            busyIndicator.IsRunning = false;
            //API.SetProgressIndicator(LayoutRoot, false, "");
        }

        private void LongListSelector_ItemRealized(object sender, ItemRealizationEventArgs e)
        {
            var itemSource = llsStories.ItemsSource;
            if (itemSource[itemSource.Count - 1] == e.Container.Content)
            {
                ExecuteSearch();
            }
        }

        private void ExecuteSearch()
        {
            if (Data.nextPage == null) return;
            var webClient = API.GetWebClient();
            webClient.DownloadStringCompleted += webClient_DownloadStringCompleted;
            webClient.DownloadStringAsync(new Uri(String.Format("http://blogtruyen.com{0}",Data.nextPage), UriKind.Absolute));
            //API.SetProgressIndicator(LayoutRoot, true, "");
        }

        private void StoryItem_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            if (StoryTap != null)
                StoryTap(sender, e);
        }
    }
}
